/**
 * Created by fanghonghui on 2017/7/17.
 */
var express = require('express');
var swig = require('swig');
var mongoose = require('mongoose');
//加载body-parser，用来处理post提交过来的数据
var bodyParser = require('body-parser');

var Cookies = require('cookies');
//app服务端对象
var app = express();
var env  = process.env.NODE_ENV||'development';
var User = require('./models/User');
var dbUrl = 'mongodb://imooc_movie_runner:F**k9001@127.0.0.1:19999/blog';
if(env=='development'){
    dbUrl = 'mongodb://localhost/blog';
}
//设置静态文件托管
//当用户访问的url以/public开始，那么直接返回对应__dirname+'/public'的文件
app.use('/public',express.static(__dirname+'/public'))

//1模板引擎的名称，同时也是模板文件的后缀，2.表示解析处理模板内容的方法
app.engine('html',swig.renderFile);

//设置模板文件的存放目录，第一个参数是必须的，第二个参数是目录
app.set('views','./views');
app.set('view engine','html');
swig.setDefaults({cache:false})

//bodyparser设置;
app.use(bodyParser.urlencoded({extended:true}));

app.use(function(req,res,next){
   req.cookies = new Cookies(req,res);
   req.userInfo = {};
   if(req.cookies.get('userInfo')){
       try{
         req.userInfo = JSON.parse(req.cookies.get('userInfo'))  ;

         //获取当前登录的用户类型
           User.findById(req.userInfo._id).then(function(userInfo){
                req.userInfo.isAdmin  = Boolean(userInfo.isAdmin);
                next();
           })
       }catch(e) {
         next();     
       }
   } else {
     next();
   }

})
/////
app.use('/admin',require('./routers/admin'))
app.use('/api',require('./routers/api'))
app.use('/',require('./routers/mian'))
mongoose.connect(dbUrl,function(err){
    if(err){
        console.log('err')
    } else {
        console.log('ok');
        app.listen(3001);
    }
});
